// AI 3D模型生成器
let scene, camera, renderer, controls;
let generatedModel;
let autoRotate = true;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    setupImageUpload();
    setupDragAndDrop();
});

function setupImageUpload() {
    const imageInput = document.getElementById('image-input');
    const previewImage = document.getElementById('preview-image');
    const imagePreview = document.getElementById('image-preview');
    
    imageInput.addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                previewImage.src = e.target.result;
                imagePreview.style.display = 'block';
                document.getElementById('upload-section').querySelector('.upload-area').style.display = 'none';
                
                // 自动开始生成
                setTimeout(() => {
                    startGeneration();
                }, 1000);
            };
            reader.readAsDataURL(file);
        }
    });
    
    document.getElementById('remove-image').addEventListener('click', function() {
        imagePreview.style.display = 'none';
        document.getElementById('upload-section').querySelector('.upload-area').style.display = 'block';
        imageInput.value = '';
    });
}

function setupDragAndDrop() {
    const uploadArea = document.querySelector('.upload-area');
    
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = '#4CAF50';
        uploadArea.style.background = 'rgba(255, 255, 255, 0.2)';
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = 'rgba(255, 255, 255, 0.3)';
        uploadArea.style.background = 'rgba(255, 255, 255, 0.1)';
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = 'rgba(255, 255, 255, 0.3)';
        uploadArea.style.background = 'rgba(255, 255, 255, 0.1)';
        
        const files = e.dataTransfer.files;
        if (files.length > 0 && files[0].type.startsWith('image/')) {
            document.getElementById('image-input').files = files;
            const event = new Event('change', { bubbles: true });
            document.getElementById('image-input').dispatchEvent(event);
        }
    });
}

function startGeneration() {
    document.getElementById('upload-section').style.display = 'none';
    document.getElementById('generation-section').style.display = 'block';
    
    // 模拟AI生成过程
    simulateGeneration();
}

function simulateGeneration() {
    const steps = [
        { step: 1, progress: 25, delay: 2000 },
        { step: 2, progress: 50, delay: 3000 },
        { step: 3, progress: 75, delay: 2500 },
        { step: 4, progress: 100, delay: 2000 }
    ];
    
    let currentStep = 0;
    
    function processNextStep() {
        if (currentStep < steps.length) {
            const step = steps[currentStep];
            
            // 更新进度条
            setTimeout(() => {
                document.getElementById('progress-fill').style.width = step.progress + '%';
                
                // 更新步骤状态
                document.querySelectorAll('.step').forEach((el, index) => {
                    el.classList.toggle('active', index < step.step);
                });
                
                currentStep++;
                setTimeout(processNextStep, step.delay);
            }, 500);
        } else {
            // 生成完成
            setTimeout(() => {
                showResult();
            }, 1000);
        }
    }
    
    processNextStep();
}

function showResult() {
    document.getElementById('generation-section').style.display = 'none';
    document.getElementById('result-section').style.display = 'block';
    
    // 初始化3D场景
    init3DScene();
    
    // 根据上传的图片生成3D模型
    generate3DModel();
}

function init3DScene() {
    const canvas = document.getElementById('result-canvas');
    
    // 创建场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x1a1a1a);
    
    // 创建相机
    camera = new THREE.PerspectiveCamera(
        45,
        canvas.clientWidth / canvas.clientHeight,
        0.1,
        1000
    );
    camera.position.set(0, 2, 5);
    
    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ 
        canvas: canvas,
        antialias: true 
    });
    renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    renderer.shadowMap.enabled = true;
    
    // 添加灯光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    scene.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(5, 10, 5);
    directionalLight.castShadow = true;
    scene.add(directionalLight);
    
    // 添加控制器
    setupControls();
    
    // 开始渲染循环
    animate();
}

function setupControls() {
    // 简化的轨道控制器
    let isDragging = false;
    let previousMousePosition = { x: 0, y: 0 };
    
    const canvas = document.getElementById('result-canvas');
    
    canvas.addEventListener('mousedown', function(e) {
        isDragging = true;
        previousMousePosition = { x: e.clientX, y: e.clientY };
    });
    
    canvas.addEventListener('mousemove', function(e) {
        if (isDragging && generatedModel) {
            const deltaMove = {
                x: e.clientX - previousMousePosition.x,
                y: e.clientY - previousMousePosition.y
            };
            
            generatedModel.rotation.y += deltaMove.x * 0.01;
            generatedModel.rotation.x += deltaMove.y * 0.01;
            
            previousMousePosition = { x: e.clientX, y: e.clientY };
        }
    });
    
    canvas.addEventListener('mouseup', function() {
        isDragging = false;
    });
    
    canvas.addEventListener('wheel', function(e) {
        e.preventDefault();
        if (generatedModel) {
            const scale = e.deltaY > 0 ? 0.9 : 1.1;
            generatedModel.scale.multiplyScalar(scale);
        }
    });
    
    // 触摸支持
    let touchStartX = 0;
    let touchStartY = 0;
    
    canvas.addEventListener('touchstart', function(e) {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
    });
    
    canvas.addEventListener('touchmove', function(e) {
        e.preventDefault();
        const touchX = e.touches[0].clientX;
        const touchY = e.touches[0].clientY;
        
        if (generatedModel) {
            generatedModel.rotation.y += (touchX - touchStartX) * 0.01;
            generatedModel.rotation.x += (touchY - touchStartY) * 0.01;
            
            touchStartX = touchX;
            touchStartY = touchY;
        }
    });
}

function generate3DModel() {
    const previewImage = document.getElementById('preview-image');
    
    // 创建基于图片的3D模型
    const geometry = new THREE.SphereGeometry(1, 64, 64);
    
    // 创建材质
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = 512;
    canvas.height = 512;
    
    // 绘制图片到纹理
    ctx.drawImage(previewImage, 0, 0, 512, 512);
    
    // 创建纹理
    const texture = new THREE.CanvasTexture(canvas);
    texture.needsUpdate = true;
    
    // 创建材质
    const material = new THREE.MeshPhongMaterial({
        map: texture,
        shininess: 100,
        specular: 0x222222
    });
    
    // 创建佛像形状（模拟）
    const buddhaGeometry = createBuddhaGeometry();
    
    // 创建模型
    generatedModel = new THREE.Mesh(buddhaGeometry, material);
    generatedModel.castShadow = true;
    generatedModel.receiveShadow = true;
    
    scene.add(generatedModel);
    
    // 添加底座
    const baseGeometry = new THREE.CylinderGeometry(1.5, 1.5, 0.2, 32);
    const baseMaterial = new THREE.MeshPhongMaterial({
        color: 0x8b4513,
        shininess: 30
    });
    const base = new THREE.Mesh(baseGeometry, baseMaterial);
    base.position.y = -1.5;
    base.receiveShadow = true;
    scene.add(base);
    
    // 更新模型信息
    updateModelInfo();
}

function createBuddhaGeometry() {
    // 创建佛像形状的简化版本
    const geometry = new THREE.SphereGeometry(1, 32, 32);
    
    // 变形为佛像形状
    const positions = geometry.attributes.position.array;
    for (let i = 0; i < positions.length; i += 3) {
        const x = positions[i];
        const y = positions[i + 1];
        const z = positions[i + 2];
        
        // 佛像头部稍微大一些
        if (y > 0.5) {
            const factor = 1 + (y - 0.5) * 0.3;
            positions[i] *= factor;
            positions[i + 2] *= factor;
        }
        
        // 佛像底部稍微宽一些
        if (y < -0.3) {
            const factor = 1.2 - y * 0.3;
            positions[i] *= factor;
            positions[i + 2] *= factor;
        }
    }
    
    geometry.attributes.position.needsUpdate = true;
    geometry.computeVertexNormals();
    
    return geometry;
}

function updateModelInfo() {
    // 模拟模型信息
    document.getElementById('vertex-count').textContent = '8,192';
    document.getElementById('face-count').textContent = '16,384';
    document.getElementById('texture-size').textContent = '512x512';
    document.getElementById('file-size').textContent = '1.8 MB';
}

function animate() {
    requestAnimationFrame(animate);
    
    if (autoRotate && generatedModel) {
        generatedModel.rotation.y += 0.005;
    }
    
    renderer.render(scene, camera);
}

function resetView() {
    if (generatedModel) {
        generatedModel.rotation.set(0, 0, 0);
        generatedModel.scale.set(1, 1, 1);
    }
    camera.position.set(0, 2, 5);
}

function toggleRotation() {
    autoRotate = !autoRotate;
    const btn = event.target;
    btn.innerHTML = autoRotate ? 
        '<i class="fas fa-pause"></i> 暂停旋转' : 
        '<i class="fas fa-play"></i> 开始旋转';
}

function downloadModel() {
    // 模拟下载功能
    alert('3D模型已准备下载！\n\n实际项目中，这里会生成并下载真实的3D模型文件。');
}

function backToUpload() {
    document.getElementById('result-section').style.display = 'none';
    document.getElementById('upload-section').style.display = 'block';
    document.getElementById('upload-section').querySelector('.upload-area').style.display = 'block';
    document.getElementById('image-preview').style.display = 'none';
    document.getElementById('image-input').value = '';
    
    // 清理3D场景
    if (scene && generatedModel) {
        scene.remove(generatedModel);
        generatedModel = null;
    }
}

// 窗口大小调整
window.addEventListener('resize', function() {
    if (renderer && camera) {
        const canvas = document.getElementById('result-canvas');
        camera.aspect = canvas.clientWidth / canvas.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    }
});
